<template>
    <view class='order-confirm-index-containter'>
        <block v-if="!defaultAddress">
            <view class="order-confirm-index-top-empty" @tap="onGotoAddAddress">
                <span class="order-confirm-index-top-add">+</span>
                <span>添加地址</span>
            </view>
        </block>
        <block v-else>
            <view class="order-confirm-index-top-had">
                <view class="order-address-top" @tap="selectAddress">
                    <view class="address-top">
                        <span class="name">{{ defaultAddress.receiverName }},</span>
                        <span class="address">{{ defaultAddress.receiverTel }}</span>
                    </view>
                    <view class="address-bottom">
                        {{
                            defaultAddress.receiverProvince + defaultAddress.receiverCity + defaultAddress.receiverArea +
                            defaultAddress.receiverAddress
                        }}
                    </view>
                </view>
                <view>
                    <image class="icon_mod" @tap="selectAddress" src="../../static/img/common/icon_mod.png" />
                </view>
            </view>
        </block>
        <block v-for="(item, index) in arrProductInfo" :key="index">
            <view class="order-confirm-goods-item-containter">
                <view class="order-confirm-goods-item-bg">
                    <image class="order-confirm-goods-item-icon" :src="item.productSquareUrl"></image>
                    <view class="order-confirm-goods-item-info">
                        <view class="order-confirm-goods-item-title">{{ item.productName }}</view>
                        <view class="order-confirm-goods-item-bottom"><span class="red">￥{{
                            item.currentPrice
                        }}</span><span>×{{ item.count }}</span>
                        </view>
                    </view>
                </view>
            </view>
        </block>
        <view class="order-confirm-index-way">
            <span class="order-confirm-index-way-left">配送方式</span>
            <span v-if="needExpressPrice" class="order-confirm-index-way-right">运费<span class="money">￥{{
                mallConfig.expressPrice
            }}</span></span>
            <span v-else class="order-confirm-index-way-right">快递免运费</span>
        </view>
        <view @tap="showPop" class="order-confirm-index-way">
            <view class="order-confirm-index-way-left">商品总额</view>
            <view class="gift_amount order-confirm-index-way-right">￥ {{ originPriceCountNoExpress }}</view>
        </view>
        <view @tap="showPop" class="order-confirm-index-way">
            <view class="order-confirm-index-way-left" v-if="selectCouponId == ''">可用优惠券</view>
            <view class="order-confirm-index-way-left" v-else>优惠</view>
            <view v-if="selectCouponId == ''" class="able_count order-confirm-index-way-right">{{ ableList.length }}张可用<span
                    class="list-item-arrow">></span></view>
            <view class="gift_amount order-confirm-index-way-right" v-else>- ￥ {{ dicountDesc }}</view>
        </view>
        <view v-if="arrProductInfo.length !== 0" class='settlement-column-tab-component-containter'>
            <view class="total">
                <block>
                    <view>合计：<span class="money">￥{{ priceCount }}</span></view>
                    <span v-if="needExpressPrice" class="tips">包含运费<span class="money">￥{{
                        mallConfig.expressPrice
                    }}</span></span>
                    <span v-else class="tips">快递免运费</span>
                </block>
            </view>
            <block>
                <view class="btn_purcharse" @tap="onPurcharse">
                    立即购买
                </view>
            </block>
        </view>
        <uni-popup background-color="#fff" ref="popup" type="bottom">
            <view class="coupon_pop">
                <view class="coupon_pop_out">
                    <radio-group @change="radioChange">
                        <label v-for="item in ableList" :key="item.id" class="coupon_detail">
                            <view class="coupon_detail_price">
                                <view v-if="item.couponConfig.type === 1" class="coupon_detail_price_detail">
                                    <view class="coupon_detail_price_unit">￥</view>
                                    <view class="coupon_detail_price_num">{{ item.couponConfig.couponAmount }}</view>
                                </view>
                                <view v-if="item.couponConfig.type === 2" class="coupon_detail_price_detail">
                                    <view class="coupon_detail_price_num">{{ item.couponConfig.couponDesc }}</view>
                                </view>
                                <view v-if="item.couponConfig.type === 3" class="coupon_detail_price_detail">
                                    <view class="coupon_detail_price_unit">赠</view>
                                    <view class="coupon_detail_price_num">{{ item.couponConfig.giftAmount }}</view>
                                </view>
                                <view>满{{ item.couponConfig.couponLimit }}元可用</view>
                            </view>
                            <view class="coupon_detail_desc">
                                <view class="coupon_detail_desc_title">{{ item.couponConfig.name }}</view>
                                <view class="coupon_detail_desc_time">有效期至{{ item.couponConfig.expire }}</view>
                            </view>
                            <radio class="coupon_radio" :value="item.id" :checked="selectCouponId == item.id" />
                        </label>
                    </radio-group>
                    <view class="no_able" v-if="ableList.length === 0">暂无可用</view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
import Big from 'big.js';
import Goods from '../components/goods';
import GoodsSquare from '../components/goodsSquare/index.vue';
import payChoose from '../components/payChoose/payChoose.vue'
import {
    mapState,
} from "vuex";
import { getCouponList } from '../../api/coupon.js';
import { getAllAddress } from '../../api/address.js';
import { cartDelete } from '../../api/cart.js';
import { wechatMini, syncOrder } from '../../api/pay.js';
// import order from '../../api/order.js';
export default {
    data() {
        return {
            defaultAddress: null,//默认地址
            arrProductInfo: [],
            cartGoodsBottomInfo: {},
            ids: [],//购物车id
            addLists: [],
            priceCount: 0,
            originPriceCountNoExpress: 0,
            isSubmit: false,
            selectAddressId: undefined,
            needExpressPrice: false,
            couponList: [],
            ableList: [],
            selectCouponId: '',
            selectCoupon: {},
            dicountDesc: '',
            currentPayWay: 3,
        }
    },
    components: {
        Goods,
        GoodsSquare,
        payChoose
    },
    computed: {
        ...mapState(["mallConfig"]),
    },
    mounted() {
    },
    methods: {
        handleNum(e) {
            this.currentPayWay = e;
        },
        radioChange: function (evt) {
            this.selectCouponId = evt.detail.value;
            this.selectCoupon = this.ableList.find((e) => e.id == evt.detail.value);
            this.$refs.popup.close();
            this.countDiscount();
        },
        countDiscount() {
            let desc = '';
            if (this.selectCoupon.couponConfig.type === 1) {//满减
                this.priceCount = this.originPriceCountNoExpress.minus(this.selectCoupon.couponConfig.couponAmount);
                desc = this.selectCoupon.couponConfig.couponAmount;
            } else if (this.selectCoupon.couponConfig.type === 2) {//打折
                let temp = 0;
                // this.priceCount = this.originPriceCountNoExpress.times(this.selectCoupon.couponConfig.discount);
                temp = this.originPriceCountNoExpress.times(100).times(this.selectCoupon.couponConfig.discount).toNumber();
                temp = new Big(Math.floor(temp));
                temp = temp.div(100);
                this.priceCount = temp;
                // desc = this.selectCoupon.couponConfig.couponAmount;
                desc = this.originPriceCountNoExpress.minus(temp);
            }
            if (this.priceCount.lte(0)) {
                this.priceCount = new Big(0.01);
            }
            this.dicountDesc = desc;
        },
        couponConfig() {
            getCouponList({
                isVirtual: false
            }).then((res) => {
                // console.log(res)
                res.data.forEach((e) => {
                    if (e.couponConfig.couponLimit !== null) {
                        e.couponConfig.originalLimit = e.couponConfig.couponLimit;
                        e.couponConfig.couponLimit = new Big(e.couponConfig.couponLimit).div(100);
                        if (e.couponConfig.type === 1) {
                            e.couponConfig.couponAmount = new Big(e.couponConfig.couponAmount).div(100);
                        }
                    }
                });
                let temp = res.data.filter((e) => e.couponStatus === 2);
                this.ableList = temp.filter((e) => this.originPriceCountNoExpress.gte(e.couponConfig.couponLimit));
                this.couponList = temp
            }).catch((err) => {
                console.log(err)
            })
        },
        addressQuery() {
            getAllAddress().then((res) => {
                // console.log(res)
                if(res.code === 200) {
                    let defaultAddress = res.data.find((e) => e.defaultType === 1);
                    if (this.selectAddressId) {
                        defaultAddress = res.data.find((e) => e.receiverId === this.selectAddressId);
                    }
                    if (defaultAddress) {
                        this.defaultAddress = defaultAddress;
                    } else if (res.data.length !== 0) {
                        this.defaultAddress = res.data[0];
                    }
                    this.addLists = res.data;
                }
            }).catch((err) => {
                console.log(err)
            })
        },
        countPrice(goodsLists) {
            let price = 0;
            let originPriceCountNoExpress = 0;
            let needExpressPrice = false;
            goodsLists.forEach((e) => {
                let x = new Big(Number(e.currentPrice))
                price = x.times(e.count).plus(price);
                originPriceCountNoExpress = x.times(e.count).plus(originPriceCountNoExpress);
            })
            console.log('this.mallConfig.expressLimit', this.mallConfig.expressLimit);
            needExpressPrice = price.lt(this.mallConfig.expressLimit);
            if (needExpressPrice) {
                price = price.plus(this.mallConfig.expressPrice);
            }
            this.priceCount = price;
            this.originPriceCountNoExpress = originPriceCountNoExpress;
            this.needExpressPrice = needExpressPrice;
            this.couponConfig();
        },
        selectAddress() {
            uni.navigateTo({
                url: '/pages/addressManager/index?from=orderConfirm',
            })
        },
        onLoad() {
            this.arrProductInfo = uni.getStorageSync("purchaseItem")
            this.countPrice(this.arrProductInfo)
            uni.getStorage({
                key: 'selectAddressId',
                success(res) {
                    that.selectAddressId = res.data;
                }
            });

			console.log('===============获取推荐人ID===============');
			console.log('===============推荐人ID:', uni.getStorageSync("agentUserId"));
        },
        onShow() {
            this.selectAddressId  = uni.getStorageSync("selectAddressId")
            this.addressQuery();
        },
        onGotoAddAddress() {
            this.selectAddress();
        },
        onPurcharse() {
            if (this.defaultAddress !== null) {
                if (this.isSubmit) {
                    return false
                }
                this.isSubmit = true;
                let data = {
                    products: [],
                    receiveAddressId: this.defaultAddress.receiverId
                }
                if (this.selectCouponId !== '') {
                    data.couponRecordId = this.selectCouponId;
                }
                let cartIds = [];
                this.arrProductInfo.forEach((e) => {
                    if (e.cartId) {
                        cartIds.push(e.cartId);
                    }
                    data.products.push({
                        productId: e.productId,
                        count: e.count,
                        price: Number(e.currentPrice)
                    })
                })
                if (cartIds.length !== 0) {
                    let params = {
                        ids: cartIds
                    }
                    cartDelete(params)
                }
                data.tradeTypeId = 1;
				data.agentUserId = uni.getStorageSync("agentUserId")
                wechatMini(data).then((res) => {
					const orderNo = res.data.orderNo
                  uni.showLoading('支付中...');
                  if (res.code === 200 && res.data !== null) {
                    wx.requestPayment({
                      timeStamp: res.data.timeStamp, //时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间
                      nonceStr: res.data.nonceStr, //随机字符串，长度为32个字符以下。
                      package: res.data.packageDate, //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
                      signType: res.data.signType, //签名类型，默认为MD5，支持HMAC-SHA256和MD5。注意此处需与统一下单的签名类型一致
                      paySign: res.data.paySign, //密钥
                      success: (res) => {
                        uni.hideLoading();
                        uni.showToast({
                          title: "支付成功",
                          icon: "none",
                        });
                        syncOrder(orderNo).then((res1) => {
                          console.log(res1)
                          uni.navigateTo({
                            url: "/pages/OrderSuccess/index"
                          })
                        }).catch((err) => {
                          setTimeout(() => {
                            uni.navigateTo({
                              url: "/pages/OrderSuccess/index"
                            })
                          }, 2000)
                        })

                      },
                      fail: (err) => {
                        uni.hideLoading();
                        uni.showToast({
                          title: "支付失败",
                          icon: "none",
                        });
                        uni.navigateTo({
                          url: `/pages/AllOrderPage/AllOrderPage?tab=product&orderType=8`
                        })
                      },
                    });
                  } else {
                    uni.showToast({
                      icon: "none",
                      title: res.msg,
                    });
                  }
                }).catch((err) => {
                    console.log(err)
                })
            } else {
                this.selectAddress();
            }
        },
        showPop() {
            this.$refs.popup.open('bottom')
        },
    }
}
</script>

<style scoped>
.order-confirm-index-containter {
    position: relative;
    width: 100%;
    height: 100%;
    padding-bottom: 130rpx;
}

.order-confirm-index-top-empty {
    background: #fff;
    height: 148rpx;
    display: flex;
    align-items: center;
    font-size: 30rpx;
    color: #333;
    line-height: 148rpx;
}

.order-confirm-index-top-had {
    background: #fff;
    height: 148rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: row;
    font-size: 30rpx;
    color: #333;
    line-height: 148rpx;
}

.order-address-top {
    flex: 1;
}

.order-confirm-index-top-add {
    font-size: 100rpx;
    margin: -20rpx 20rpx 0 50rpx;
}

.order-confirm-index-way {
    margin: 20rpx 0 0 4%;
    width: 92%;
    height: 88rpx;
    background: rgba(255, 255, 255, 1);
    border-radius: 10rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 26rpx;
    color: rgba(51, 51, 51, 1);
}

.order-confirm-index-way-left {
    margin-left: 30rpx;
}

.order-confirm-index-way-right {
    margin-right: 30rpx;
}

.address-top {
    font-size: 26rpx;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    line-height: 36rpx;
    width: 88%;
    padding: 0 6%;
}

.address-bottom {
    font-size: 22rpx;
    color: rgba(85, 85, 85, 1);
    line-height: 36rpx;
    width: 88%;
    padding: 0 6%;
    overflow-x: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.icon_mod {
    width: 30rpx;
    height: 30rpx;
    margin-right: 30rpx;
}

.order-confirm-goods-item-containter {
    position: relative;
    width: 100%;
    margin-top: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.order-confirm-goods-item-bg {
    height: 270rpx;
    width: 92%;
    background: #fff;
    border-radius: 10rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.order-confirm-goods-item-icon {
    width: 145rpx;
    height: 145rpx;
}

.order-confirm-goods-item-info {
    width: calc(100% - 274rpx);
    margin-left: 80rpx;
}

.order-confirm-goods-item-title {
    font-size: 24rpx;
    color: #333;
}

.order-confirm-goods-item-bottom {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: space-between;

    font-size: 24rpx;
    color: #333;
    line-height: 80rpx;
}

.red {
    font-size: 28rpx;
    font-weight: bold;
    color: rgba(242, 85, 0, 1);
}

settlement-column-tab-component {
    width: 100%;
}

.settlement-column-tab-component-containter {
    position: fixed;
    bottom: 0%;
    width: 100%;
    height: 130rpx;
    background: rgba(255, 255, 255, 1);
    border-top: 1rpx solid rgba(245, 245, 245, 1);
    overflow: hidden;
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: space-between;
    z-index: 10;
}

.settlement-column-tab-component-containter .circle {
    width: 42rpx;
    height: 44rpx;
    margin: 0 0 0 50rpx;
}

.settlement-column-tab-component-containter .all {
    font-size: 26rpx;
    color: rgba(51, 51, 51, 1);
    line-height: 48rpx;
    margin: 0 0 0 20rpx;
}

.settlement-column-tab-component-containter .total {
    width: calc(100% - 300rpx);
    text-align: right;
    font-size: 26rpx;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
}

.settlement-column-tab-component-containter .total .tips {
    font-size: 20rpx;
    font-weight: 400;
    color: rgba(102, 102, 102, 1);
}

.settlement-column-tab-component-containter .btn_purcharse {
    width: 250rpx;
    height: 130rpx;
    background: linear-gradient(90deg,
            rgba(242, 85, 0, 1) 0%,
            rgba(252, 67, 83, 1) 100%);
    font-size: 26rpx;
    font-weight: 500;
    color: rgba(255, 255, 255, 1);
    line-height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.money {
    color: red;
}


.coupon_select {
    display: flex;
    justify-content: space-between;
    margin-top: 20rpx;
    padding: 30rpx 50rpx;
    background-color: #fff;
    font-size: 26rpx;
}

.able_count {
    color: #e43930;
}

.coupon_pop {
    padding: 30rpx 0;
}

.coupon_pop_out {
    height: 650rpx;
    overflow: auto;
}

.coupon_detail {
    display: flex;
    background-color: #F6F6F6;
    height: 190rpx;
    margin: 30rpx;
    border-radius: 10rpx;
}

.coupon_detail_desc {
    flex: 1;
    padding-top: 50rpx;
    text-align: center;
}

.coupon_detail_desc_title {
    font-size: 30rpx;
    margin-bottom: 10rpx;
}

.coupon_detail_desc_time {
    font-size: 24rpx;
    color: #999999;
}

.coupon_detail_price {
    flex: 0 0 240rpx;
    color: #f25500;
    padding-top: 20rpx;
    box-sizing: border-box;
    text-align: center;
}

.coupon_detail_price_detail {
    display: flex;
    margin-bottom: 10rpx;
    align-items: baseline;
    text-align: center;
    justify-content: center;
    padding-right: 10rpx;
}

.coupon_detail_price_unit {
    font-size: 30rpx;
}

.coupon_detail_price_num {
    font-size: 60rpx;
}

.coupon_radio {
    align-self: center;
}

.gift_amount {
    color: #e4393c;
}

.no_able {
    text-align: center;
    margin-top: 50rpx;
}
</style>
